package cn.catsdad.tenant.runner;

import cn.catsdad.base.repository.IBaseTenantRepository;
import cn.catsdad.constant.ICommonWarningType;
import cn.catsdad.tenant.sqlInspector.EntityDefinition;
import cn.catsdad.tenant.sqlInspector.TenantEntityRegistry;
import cn.catsdad.util.ReflectUtil;
import cn.catsdad.util.SpringContextUtil;
import cn.catsdad.util.StringUtil;
import jakarta.persistence.Table;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.data.jpa.repository.support.JpaEntityInformation;
import org.springframework.stereotype.Component;

import java.util.Collection;
import java.util.Map;

/**
 * 租户表注册，项目启动后登记所有的租户表信息
 *
 * @author xuyl
 * @version V1.0.0 2024/8/2
 * @since V100R001
 */
@Component
@SuppressWarnings(ICommonWarningType.ALL)
public class TenantRegisterRunner implements ApplicationRunner {
    @Override
    public void run(ApplicationArguments args) throws Exception {
        Map<String, IBaseTenantRepository> tenantRepositoryMap = SpringContextUtil.getBeanOfType(IBaseTenantRepository.class);
        Collection<IBaseTenantRepository> values = tenantRepositoryMap.values();
        TenantEntityRegistry tenantEntityRegistry = SpringContextUtil.getBean(TenantEntityRegistry.class);
        if (StringUtil.isNotEmpty(values)) {
            for (IBaseTenantRepository value : values) {
                JpaEntityInformation entityInfo = value.getEntityInfo();
                Class entityClass = value.getEntityClass();
                Object tableName = ReflectUtil.getAnnotationValue(entityClass, Table.class, "name");
                if (tableName instanceof String) {
                    EntityDefinition entityDefinition = new EntityDefinition().setEntityName(entityClass.getName())
                            .setSimpleEntityName(entityInfo.getEntityName())
                            .setTableName(tableName.toString().trim())
                            .setQueryAlias(value.getQueryAlias());
                    tenantEntityRegistry.registerEntity(entityClass.getName(), entityDefinition);
                }
            }
        }
    }
}
